package leetCode.sample;

import org.junit.Test;

import java.util.Arrays;

public class ThreeSumClosestSolution {

    @Test
    public void test(){

        //System.out.println(threeSumClosest(new int[]{-1,2,1,-4},1));
        System.out.println(threeSumClosest(new int[]{1,2,4,8,16,32,64,128},82));
    }

    public int threeSumClosest(int[] nums, int target) {
        int result = 0;
        int diff = Integer.MAX_VALUE;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            int x = nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int tmp = nums[left] + nums[right] + x;
                if(Math.abs(tmp-target)<diff){
                    diff = Math.abs(tmp-target);
                    result = tmp;
                }
                if(diff == 0){
                    return result;
                }
                if (tmp > target) {
                    while (left < right && nums[right] == nums[--right]) {

                    }
                } else if (tmp < target) {
                    while (left < right && nums[left] == nums[++left]) {

                    }
                } else {
                    while (left < right && nums[right] == nums[--right]) ;
                    while (left < right && nums[left] == nums[++left]) ;
                }
            }
        }
        return result;
    }
}
